package com.example.distributesession.config;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    String userName = "root";
    String passWord = "rootroot";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来请求了");
        //1、先从参数里面获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        HttpSession session = req.getSession();
        //2、然后从session里面获取用户名，如果获取到了，而且和浏览器传过来的是一样的，那么就说明用户已经登陆。
        if (session.getAttribute("username") != null
                && session.getAttribute("username").equals(username)) {
            resp.getWriter().write("you has login, no need reLogin");
            return;
        }
        //3、那如果session里面是没有用户名的，那么就说明之前没登录过，需要重新做用户名密码的认证。
        if (userName.equals(username) && passWord.equals(password)) {
            //4、认证成功，返回登陆成功，认证失败，返回认证失败。
            session.setAttribute("username", username);
            resp.getWriter().write("login success");
        } else {
            resp.getWriter().write("login fail");
        }
    }
}